package com.zhibang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhibang.entity.Menu;
import com.zhibang.mapstruct.MenuMapstruct;
import com.zhibang.service.MenuService;
import com.zhibang.mapper.MenuMapper;
import com.zhibang.vo.IndexMenuVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static java.awt.SystemColor.menu;

/**
* @author lewin
* @description 针对表【menu(菜单表)】的数据库操作Service实现
* @createDate 2025-03-05 09:18:16
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{

    @Resource
    MenuMapper mm;

    @Override
    public List<IndexMenuVo> initMenu(Integer aid) {
        String mid =mm.getMenuById(aid);
//        分割出菜单id
        String[] idArr=mid.split(",");
//        条件构造器
        QueryWrapper<Menu> qw = new QueryWrapper<>();
        qw.in("id",idArr);
        qw.eq("type","菜单");
        List<Menu> menus =list(qw);
//        提取出顶层菜单
        Menu parentMenu = menus.stream().filter(m -> m.getId() == 1)
                .findFirst().get();
//        返回二级和三级目录
        List<IndexMenuVo> vos = buildTreeMenu(menus, parentMenu.getId());
        return vos;
    }
    

//    构建树形菜单
    public List<IndexMenuVo> buildTreeMenu(List<Menu> menus,Integer pid){
//        创建一个vo集合
        List<IndexMenuVo> vos = new ArrayList<>();
//       取出子集菜单
        List<Menu> childMenu = menus.stream().filter(m -> m.getPid().equals(pid))
                .collect(Collectors.toList());
//        遍历子集，递归下一层数据
        for (Menu menu : childMenu){
            IndexMenuVo vo = MenuMapstruct.instance.toIndexMenuVo(menu);
//            递归当前菜单下的子集
            List<IndexMenuVo> child = buildTreeMenu(menus, menu.getId());
            vo.setChildren(child);
            vos.add(vo);
        }
        return vos;
    }
}




